<template>
    <!-- 顶部 -->
    <div class="topTitle">
        客服聊天
    </div>
    <div class="topk">.</div>
    <!-- 聊天 -->
    <div class="container">
        <div class="msgs">
            <div v-for="item in csList" :key="item._id" :class="['msga', item.userid == userID ? 'nomy' : 'my']">
                <img :src="item.userid == userID ? userAvatar : csAvatar" alt="avatar" class="avatar" />
                <div class="msgC">
                    <div :class="['msgH', item.userid == userID ? 'nomy' : 'my']">
                        <strong>{{ item.userid == userID ? userName : '客服' }}</strong>
                    </div>
                    <div class="msgB">
                        <p>{{ item.message }}</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="inp">
            <input v-model="newMsg" type="text" placeholder="输入消息..." @keydown.enter="sendMsg" />
            <button @click="sendMsg">发送</button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onBeforeUnmount, onMounted, ref } from 'vue';
import apiClient from "../../api";
import { wsUrl } from "../../api";
import axios from 'axios';

let csAvatar = "https://img2.baidu.com/it/u=4083171843,1016119090&fm=253&fmt=auto&app=138&f=JPEG";
let userID = ref(JSON.parse(sessionStorage.getItem('_id') || '""') || '');
let userName = ref(JSON.parse(sessionStorage.getItem('username') || '""') || '');
let userAvatar = ref(JSON.parse(sessionStorage.getItem('pic') || '""') || '');
let csList = ref([
    {
        userid: '1',
        message: '你好，有什么可以帮助你的吗？',
    },
]);
let ws: WebSocket | null = null;
let newMsg = ref('');

let sendMsg = () => {
    if (newMsg.value.trim() === '' || !ws || ws.readyState !== WebSocket.OPEN) return;
    ws.send(JSON.stringify({
        userid: userID.value,
        message: newMsg.value
    }))
    newMsg.value = '';
};

let goWs = () => {
    ws = new WebSocket(wsUrl);
    ws.onopen = () => {
        console.log('连接成功');
    };
    ws.onmessage = (e) => {
        csList.value.push(JSON.parse(e.data));
    };
    ws.onclose = () => {
        console.log('连接关闭');
    };
    ws.onerror = (event) => {
        console.log('连接出错', event);
    };
};

let axiosAPI = () => {
    axios.get("ch/getChatHistory").then((res) => {
        csList.value = (res.data);
        goWs();
    })
};
let updateAPI = () => {
    axios.post("ch/getChatHistory", csList.value).then((res) => {
        console.log(res)
    })
};

onBeforeMount(() => {
});
onMounted(() => {
    axiosAPI();
});

onBeforeUnmount(() => {
    updateAPI()
    if (ws) {
        ws.close();
    }
});
</script>

<style scoped>
.topTitle {
  text-align: center;
  font-weight: 600;
  padding: 1em 0;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 999
}

.topk {
  text-align: center;
  font-weight: 600;
  padding: 1em 0;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 16px;
  max-width: 100%;
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #ddd;
  /* border-radius: 8px; */
  background-color: #f9f9f9;
  height: 84vh;
  /* 使页面占满整个视口高度 */
  position: relative;
  /* 为了放置输入框在底部 */
}

.msgs {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 80px;
  /* 确保消息区域不被输入框遮挡 */
}

.msga {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}

.msga.my {
  flex-direction: row;
  /* 对方消息左侧 */
  align-self: flex-start;
}

.msga.nomy {
  flex-direction: row-reverse;
  /* 用户消息右侧 */
  align-self: flex-end;
}

.msga .avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  margin-top: 4px;
  /* 头像稍微低一点 */
}

.msga.nomy .avatar {
  margin-left: 10px;
  margin-right: 0;
}

.msga.my .avatar {
  margin-left: 0;
  margin-right: 10px;
}

.msga .msgC {
  display: flex;
  flex-direction: column;
  max-width: 80%;
}

.msga .msgH {
  color: #ccc;
  font-size: 14px;
  margin-bottom: 2px;
  /* 使名字靠近头像 */
  text-align: left;
  /* 默认左对齐 */
}

.msga.my .msgH {
  text-align: left;
  /* 我的名字靠右 */
}

.msga.nomy .msgH {
  text-align: right;
  /* 客服名字靠左 */
}

.msga .msgB {
  padding: 8px;
  border-radius: 8px;
}

.msga.nomy .msgB {
  background-color: #e1ffc7;
}

.msga.my .msgB {
  background-color: #ffffff;
}

.msga p {
  margin: 0;
  font-size: 16px;
}

.inp {
  display: flex;
  align-items: center;
  position: fixed;
  /* 固定在页面底部 */
  bottom: 60px;
  /* 从底部偏移60px */
  left: 16px;
  /* 从左侧偏移16px */
  right: 16px;
  /* 从右侧偏移16px */
  padding: 10px;
  border-top: 1px solid #ddd;
  background-color: #ffffff;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
  z-index: 10;
  /* 确保在其他元素上方 */
}

.inp input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 12px;
  /* 增加右侧间距 */
}

.inp button {
    padding: 8px 16px;
    /* 增加按钮左右内边距 */
    border: none;
    border-radius: 4px;
    background-color: #ff6380;
    color: white;
    cursor: pointer;
}

.inp button:hover {
    background-color: #ff6380;
}
</style>